import { defineStore } from 'pinia';
import { reqCode, reqUserLogin } from '@/api/hospital';
import { LoginData, UserInfo, UserLoginResponseData } from '@/api/hospital/type';
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/user";
import { UserState } from './interface';

const useUserStore = defineStore('User', {
    state: (): UserState => {
        return {
            visiable: false,
            code: '',
            userInfo: (JSON.parse(GET_TOKEN() as string) || {} as UserInfo)
        }
    },
    getters: {
    },
    actions: {
        async getCode(phone: string) {
            const result: any = await reqCode(phone);
            if (result.code == 200) {
                this.code = result.data;
                return 'ok'
            } else {
                return Promise.reject(new Error("获取验证码失败。错误码：" + result.code))
            }
        },
        async userLogin(loginData: LoginData) {
            let result: UserLoginResponseData = await reqUserLogin(loginData);
            if (result.code == 200) {
                this.userInfo = result.data;
                //本地存储持久化存储用户信息
                SET_TOKEN(JSON.stringify(this.userInfo));
                //返回一个成功的Promise
                return 'ok';
            } else {
                return Promise.reject(new Error(result.message));
            }
        },
        logout() {
            //清空仓库的数据
            this.userInfo = { name: '', token: '' };
            //清空本地存储的数据
            REMOVE_TOKEN();
        },
        // 查询微信扫码的接口(看本地存储是否存储数据)
        queryState() {
            //开启定时器每隔一段时间问:本地村是都拥有用户信息
            let timer = setInterval(() => {
                if (GET_TOKEN()){
                    //有用户数据，关闭对话框
                    this.visiable = false;
                    this.userInfo = JSON.parse(GET_TOKEN() as string);
                    clearInterval(timer);
                }
            }, 1000);
        },
    }
});

export default useUserStore;